package com.zzyy.study.service;

import cn.hutool.core.util.IdUtil;
import com.zzyy.study.entities.User;
import com.zzyy.study.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.concurrent.TimeUnit;

/**
 * @auther zzyy
 * @create 2024-04-03 15:51
 */
@Service
public class UserLongTXService
{
    @Resource
    private UserMapper userMapper;
    @Resource
    private TransactionTemplate transactionTemplate;


    public String costTimeMethod()
    {
        try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); }
        return IdUtil.simpleUUID().substring(0,8);
    }

    @Transactional //下面有个故意耗时的方法且和@Transactional一起使用中
    public int addUser(User user)
    {
        //1 某个方法超级耗时获得用户名字拼装数据，故意耗时
        String userName = user.getUsername()+"-"+costTimeMethod();
        user.setUsername(userName);
        //2 插入数据库成功返回
        return userMapper.insertSelective(user);
    }








    /**
     * 优化后的方法，脑袋上没有    @Transactional注解
     * @param user
     * @return
     */
    public int addUserOptimize(User user)
    {
        //1 某个方法超级耗时获得用户名字拼装数据，故意耗时
        String userName = user.getUsername()+"-"+costTimeMethod();
        user.setUsername(userName);

        /**
         transactionTemplate.execute(new TransactionCallback<Object>()
         {
             @Override
             public Object doInTransaction(TransactionStatus status)
             {
                return userMapper.insertSelective(user);
             }
         });
         */

        return transactionTemplate.execute(status -> userMapper.insertSelective(user));
    }
}


